package com.chare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chare.mapper.AdminMapper;
import com.chare.mapper.RoleMapper;
import com.chare.pojo.Admin;
import com.chare.pojo.RespBean;
import com.chare.pojo.Role;
import com.chare.service.IAdminService;
import com.chare.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shi
 * @since 2022-06-17
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
   private   UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private  AdminMapper mapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public RespBean login(String username, String password,String code,HttpServletRequest request) {
/*        PasswordEncoder passwordEncoder=new SCryptPasswordEncoder();*/

        String code1= (String) request.getSession().getAttribute("captcha");
        if(code1==null||!code1.equalsIgnoreCase(code))
        {
            return RespBean.error("验证码错误请重新输入");
        }
        UserDetails userDetails=userDetailsService.loadUserByUsername(username);
        System.out.println(passwordEncoder.encode(password));
        if (userDetails==null||!passwordEncoder.matches(password,userDetails.getPassword())) {
            throw new UsernameNotFoundException("用户名和密码异常");
        }
        //判断当前对象是否可用
        if(!userDetails.isEnabled())
        {
            return  RespBean.error("用户状态异常");
        }
        //将用户的基本信息存放在security
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

     //   request.setAttribute("kk",userDetails.getUsername());

        //如果登录成功生成一个令牌
           String token= jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> map=new HashMap<>();
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return RespBean.success("登陆成功",map);
    }
//通过用户名查用户
    @Override
    public Admin getAdminByUserName(String username) {
        return mapper.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled",true));
    }
    //通过用户id查角色来获得权限
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }
/*    获得所有操作员信息*/
    @Override
    public List<Admin> getAllAdmin(String keywords) {
        Principal principal= SecurityContextHolder.getContext().getAuthentication();
        String name= principal.getName();
        System.out.println(name);
        Admin admin=mapper.selectOne( new QueryWrapper<Admin>().eq("username",name));
        Integer id=admin.getId();
        return mapper.gerAllAdmin(id,keywords);
    }


}
